public with sharing class preRegistrationController {
    //PO Added 7/15/2014
    public String licenseNo {get;set;}
    public string sawahiEmail {get;set;}
    public boolean displaySuccess {get;set;}
    public boolean displayRegistration {get;set;}
    public List<Contact> contactList {get;set;}
    public Contact contactInserted {get;set;}
    public string contactID = null;
    public List<Account> accountList {get;set;}
   // private Map<Id,Contact> contactMap = new Map<Id,Contact>();

    //constructors
    public preRegistrationController(ApexPages.StandardController controller){
       //this.con = (contact) controller.getRecord();
       if(ApexPages.CurrentPage().getParameters().get('cntc') != null)
       contactID = ApexPages.CurrentPage().getParameters().get('cntc');
       displaySuccess = false;
       displayRegistration = true;
    }

	public pageReference checkSawahi(){
		if(licenseNo == null || licenseNo == ''){
			ApexPages.Message msg= new ApexPages.Message(ApexPages.Severity.Error, 'License number is required');
			ApexPages.addMessage(msg);
		}
		if(sawahiEmail == null || sawahiEmail == ''){
			ApexPages.Message msg= new ApexPages.Message(ApexPages.Severity.Error, 'Sawahi email is required');
			ApexPages.addMessage(msg);
		}
		List<ApexPages.Message> msgList = ApexPages.getMessages();
		if(msgList.size() > 0){
			return null;
		} else {
			//check if sawahi exists in the users
			String email = string.escapeSingleQuotes(sawahiEmail);
			List<String> sawahiId = email.split('@');
			List<User> userList = [Select id, isActive, username from User where  profile.name='AFZA Mobile App Users' and username=:email LIMIT 1];
			
			if(userList.size() > 0){
				ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error,'You have already registered for Mobile APP Services. Please login using your Sawahi Email Credentials');
				ApexPages.addMessage(msg);
				return null;
			} else {
				String licenseNumber = string.escapeSingleQuotes(licenseNo);
				accountList = [Select Id, MyAFZA_Account_ID__c from Account where LicenseNumber__r.Name=:licenseNo and MyAFZA_Account_ID__c=:sawahiId[0] LIMIT 1];
				
				if(accountList.size() > 0){
					//Custom Settings
					List<Master_Account__c> maList = Master_Account__c.getAll().values();
					String accountId = maList.get(0).Id__c;
					//create contact 
					Contact contactObject = new Contact();
					contactObject.LastName = accountList.get(0).MyAFZA_Account_ID__c + '@myafza.ae';
					contactObject.Gender__c = 'Company';
					contactObject.AccountId = accountList.get(0).Id;
					
					
					try{
						insert contactObject;	
					} 
					 catch (Exception e)
					 {
					    ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Registration failed'+  e.getLineNumber());
				        ApexPages.addMessage(myMsg);
				        return null;
					 	
					 }
					//create community user
			        try
				         {
					        //Now Creating the Portal  Community User...
					        User userObject = new User();
					                
					        userObject.username = accountList.get(0).MyAFZA_Account_ID__c.trim().toLowerCase() + '@myafza.ae';
					        System.debug('The Username : '+ userObject.username);
					        userObject.email = userObject.username;
					        userObject.lastName = contactObject.LastName;
					        //userObject.firstName = contactObject.LastName;
					        //userObject.accountId = accountList.get(0).id;
					        String alias = userObject.username;
					        if(alias.length() > 8) {
					           alias = alias.substring(0, 8);
					        }
					        userObject.alias = alias;
					        userObject.CommunityNickname = alias + Math.random();
					        userObject.languagelocalekey = 'en_US';
					        userObject.localesidkey = 'en_US';
					        userObject.emailEncodingKey = 'UTF-8';
					        userObject.timeZoneSidKey = 'Asia/Dubai';
					        userObject.ContactId = contactObject.Id;
					        userObject.profileId = [SELECT Id FROM profile WHERE name='AFZA Mobile APP Users'].Id;
					        
					        //remove salesforce1 option
					        userObject.UserPermissionsMobileUser = false;
					        userObject.UserPermissionsChatterAnswersUser = false;
					                
					        //For setting the DML Opertaions...
					        Database.DMLOptions dmo = new Database.DMLOptions();
					        //no emails
					        dmo.EmailHeader.triggerUserEmail = false;
					                
					        userObject.setOptions(dmo);
					                
					        //insert userObject;
					        Database.SaveResult userInsertList = Database.insert(userObject,dmo );    
					        system.debug('## userInsertList =>' + userInsertList);
					        if (userInsertList.isSuccess()) {
					        // Operation was successful, so get the ID of the record that was processed
					            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Registration Successful. Please Login with your Sawahi Id');
					            ApexPages.addMessage(myMsg);
					            displaySuccess = true;
					            displayRegistration = false;
					            PageReference pageRef = new PageReference('/apex/MobileAppRegistrationConfirm');
					            return pageRef;
					        } else {
					            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Error,'Registration failed' + userInsertList.getErrors());
					            ApexPages.addMessage(myMsg);
					            return null;
					
					        }
					        } catch (Exception err)
					        {
					            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Registration failed' + err.getMessage() + err.getlineNumber());
					            ApexPages.addMessage(myMsg);
					            return null;
					        }			
					
					
					
				} else {
					ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error,'There was no match found. Please enter your Company License Number and  Sawahi email');
					ApexPages.addMessage(msg);
					return null;					
				}
				
				return null;
			}
			
		}
		

	}	
	
	public PageReference registerPortalUser() {
	   //retreive contact details
	   Contact contactObject = contactInserted;
       try
         {
	        //Now Creating the Portal  Community User...
	        User userObject = new User();
	                
	        userObject.username = contactObject.Current_Employer__r.MyAFZA_Account_ID__c.trim().toLowerCase() + '@myafza.ae';
	        System.debug('The Username : '+ userObject.username);
	        userObject.email = userObject.username;
	        userObject.lastName = contactObject.LastName;
	        userObject.firstName = contactObject.LastName;
	        //userObject.accountId = contactObject.Current_Employer__r.id;
	        String alias = userObject.username;
	        if(alias.length() > 8) {
	           alias = alias.substring(0, 8);
	        }
	        userObject.alias = alias;
	        userObject.CommunityNickname = alias + Math.random();
	        userObject.languagelocalekey = 'en_US';
	        userObject.localesidkey = 'en_US';
	        userObject.emailEncodingKey = 'UTF-8';
	        userObject.timeZoneSidKey = 'Asia/Dubai';
	        userObject.ContactId = contactObject.Id;
	        userObject.profileId = [SELECT Id FROM profile WHERE name='AFZA Mobile APP Users'].Id;
	                
	        //For setting the DML Opertaions...
	        Database.DMLOptions dmo = new Database.DMLOptions();
	        //no emails
	        dmo.EmailHeader.triggerUserEmail = false;
	                
	        userObject.setOptions(dmo);
	                
	        //insert userObject;
	        Database.SaveResult userList = Database.insert(userObject,dmo );    
	        system.debug('## userList =>' + userList);
	        if (userList.isSuccess()) {
	        // Operation was successful, so get the ID of the record that was processed
	            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Registration Successful. Please Login with your Sawahi Id');
	            ApexPages.addMessage(myMsg);
	            return null;
	        } else {
	            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Error,'Registration failed' + userList.getErrors());
	            ApexPages.addMessage(myMsg);
	            return null;
	
	        }
	        } catch (Exception err)
	        {
	            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Registration failed' + err.getMessage());
	            ApexPages.addMessage(myMsg);
	            return null;
	        }			
	}


    public pageReference createPortalUser(){
        Contact contactObject = [Select Id, FirstName, Email, Current_Employer__r.id, Current_Employer__r.Name, Current_Employer__r.MyAFZA_Account_ID__c from Contact where id=:contactId];
       
       try
         {
        //Now Creating the Portal  Community User...
        User userObject = new User();
                
        userObject.username = contactObject.Current_Employer__r.MyAFZA_Account_ID__c.trim().toLowerCase() + '@myafza.ae';
        System.debug('The Username : '+ userObject.username);
        userObject.email = userObject.username;
        userObject.lastName = contactObject.FirstName;
        //userObject.accountId = contactObject.Current_Employer__r.id;
        String alias = userObject.username;
        if(alias.length() > 8) {
           alias = alias.substring(0, 8);
        }
        userObject.alias = alias;
        userObject.CommunityNickname = alias + Math.random();
        userObject.languagelocalekey = 'en_US';
        userObject.localesidkey = 'en_US';
        userObject.emailEncodingKey = 'UTF-8';
        userObject.timeZoneSidKey = 'Asia/Dubai';
        userObject.ContactId = contactObject.Id;
        userObject.profileId = [SELECT Id FROM profile WHERE name='AFZA Mobile APP Users'].Id;
                
        //For setting the DML Opertaions...
        Database.DMLOptions dmo = new Database.DMLOptions();
        //no emails
        dmo.EmailHeader.triggerUserEmail = false;
                
        userObject.setOptions(dmo);
                
        //insert userObject;
        Database.SaveResult userList = Database.insert(userObject,dmo );    
        system.debug('## userList =>' + userList);
        if (userList.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        //System.debug('Successfully inserted account. Account ID: ' + sr.getId());
            return new PageReference('/' + contactId);
        } else {
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Registration failed' + userList.getErrors());
            ApexPages.addMessage(myMsg);
            return null;

        }
        } catch (Exception err)
        {

            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Registration failed' + err.getMessage());
            ApexPages.addMessage(myMsg);
            return null;
        }
        
    }
}